<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\SalePerformance;
use App\Enums\DataPermission;
use App\Enums\OptionType;
use App\Enums\SalePerformanceType;
use App\Exceptions\AdminInvalidRequestException;
use App\Helpers\KeyHandler;
use App\Models\User;
use App\Services\OptionService;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController as BaseController;
use Dcat\Admin\Show;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Route;

class AdminController extends BaseController
{

    /**
     * 是否有新增功能
     * @var bool
     */
    public bool $create = true;
    /**
     * 新增功能的权限名称
     * @var string
     */
    public string $create_permission_name = '';
    /**
     * 是否有编辑功能
     * @var bool
     */
    public bool $edit = true;
    /**
     * 编辑功能的权限名称
     * @var string
     */
    public string $edit_permission_name = '';
    /**
     * 是否有删除功能
     * @var bool
     */
    public bool $delete = true;
    /**
     * 删除功能的权限名称
     * @var string
     */
    public string $delete_permission_name = '';


    /**
     *  开启字段选择器功能
     * @var bool
     */
    public bool $show_column_selector = true;

    /**
     * 手机模式列隐藏的字段
     * @var array
     */
    public array $mobile_hide_columns = [];


    /**
     * 正常模式列隐藏的字段
     * @var array
     */
    public array $normal_hide_columns = [];


    /**
     *  禁用分页
     * @var bool
     */
    public bool $disable_pagination = false;


    /**
     *  禁用行操作
     * @var bool
     */
    public bool $disable_actions = false;


    /**
     * 是否开启窗口添加模式
     * @var bool
     */
    public bool $enable_dialog_create = true;


//    public function __construct()
//    {
//        $action = Route::current()->getActionName();
//        list($controller) = explode('@', $action);
//        $controller = Str::kebab(Str::replace('Controller', '', substr(strrchr($controller, '\\'), 1)));
//        $this->create_permission_name = $controller . '-create';
//        $this->edit_permission_name = $controller . '-edit';
//        $this->delete_permission_name = $controller . '-delete';
//    }


    //表格的公共操作
    public function gridCommon(Grid $grid)
    {
        //添加
//        if (!$this->create || ($this->create && Admin::user()->cannot($this->create_permission_name))) {
//            $grid->disableCreateButton();
//        } else {
//            $this->enable_dialog_create && $grid->enableDialogCreate();
//        }
//        //修改
//        if ($this->edit && Admin::user()->can($this->edit_permission_name) && !$this->isTrashed()) {
//            $this->enable_dialog_create ? $grid->showQuickEditButton() : $grid->showEditButton();
//        }
//        //删除
//        if (!$this->delete || ($this->delete && Admin::user()->cannot($this->delete_permission_name)) || $this->isTrashed()) {
//            $grid->disableDeleteButton();
//        }

        if ($this->show_column_selector) {
            //默认隐藏的行
            $grid->showColumnSelector();
            if (isMobileDevice()) {
                $grid->hideColumns($this->mobile_hide_columns);
            } else {
                $grid->hideColumns($this->normal_hide_columns);
            }
        }

        //关闭分页
        if ($this->disable_pagination) {
            $grid->disablePagination();
        }

        //禁用行操作
        if ($this->disable_actions) {
            $grid->disableActions();
        }
    }


    /**
     * 获取管理员对应角色的数据权限
     * @return int
     */
    public function getAdminDataPermission(): int
    {
        //因为设置了单角色，所以取第一个
        $role = Arr::first(Admin::user()->roles);
        return $role->data_permission;
    }


    //获取当前管理员的角色
    public function getAdminUserRole()
    {
        return Arr::first(Admin::user()->roles);
    }


    //判断用户是否只能查看自己的数据，并追加对应的查询条件
    public function adminDataPermissionQuery($grid)
    {
        $data_permission = $this->getAdminDataPermission();
        $user = self::getUserInfo();
        $grid->model()
            ->when($data_permission == DataPermission::SELF, function (Builder $builder) {
                $builder->where('user_id', '=', self::getUserId());
            })
            ->when($data_permission == DataPermission::DEPARTMENT, function (Builder $builder) use ($user) {
                //部门数据
                $builder->whereHas('user', function (Builder $query) use ($user) {
                    $query->where('ding_id', $user->ding_id)
                        ->where('dept_id', $user->dept_id);
                });
            })
            ->when($data_permission == DataPermission::BRAND, function (Builder $builder) use ($user) {
                //品牌资质数据
                $builder->whereHas('customer', function (Builder $query) use ($user) {
                    $query->where('brand_option_id', '=', $user->brand_option_id ?? 0);
                });
            })
            ->orderByDesc('id');
    }


    public function getAdminUserId()
    {
        return Admin::user()->id;
    }

    /**
     *
     * 获取当前管理员对应的员工id
     * @return int
     */
    public static function getUserId(): int
    {
        $user = self::getUserInfo();
        return $user->id ?? 0;
    }

    /**
     *
     * 获取当前管理员对应的员工信息
     * @return User|null
     */
    public static function getUserInfo(): User|null
    {
        return Cache::remember(sprintf(KeyHandler::ADMIN_USER_INFO, Admin::user()->id), KeyHandler::ADMIN_USER_INFO_TTL, function () {
            return User::query()->where('admin_user_id', Admin::user()->id)->first();
        });
    }

    /**
     * 详情显示客户的基本信息(需关联客户模型)
     * @param Show $show
     */
    public function customerInfo(Show $show)
    {
        $show->field('customer.name', trans('customer.fields.name'));
        $show->field('customer.phone', trans('customer.fields.phone'));
        $show->field('customer.wechat', trans('customer.fields.wechat'));
        $show->field('customer.qq', trans('customer.fields.qq'));
    }


    //获取列表的客户基本信息
    public function girdCustomerInfo($grid)
    {
        $grid->column('customer.name', trans('customer.fields.name'));
        $grid->column('customer.phone', trans('customer.fields.phone'));
        $grid->column('customer.wechat', trans('customer.fields.wechat'));
        $grid->column('customer.qq', trans('customer.fields.qq'));
    }


    //判断当前是否是回收站，如果是回收站需要关闭操作相关的功能
    public function isTrashed(): bool
    {
        return request('_scope_') == 'trashed';
    }


    public function salePerformanceEdit(): Form
    {
        return Form::make(SalePerformance::with(['customer']), function (Form $form) {
            $form->text('customer.name', trans('customer.fields.name'))->readOnly();
            $form->text('customer.phone', trans('customer.fields.phone'))->readOnly();
            $form->text('type_str', trans('sale-performance.fields.type'))->default(SalePerformanceType::getDescription($form->model()->type), true)->readOnly();
            if ($form->model()->deposit == 0 && $form->model()->balance == 0) {
                $form->number('money', trans('sale-performance.fields.total_money'))->min(1)->max(999999)->required();
            } else {
                $form->number('deposit', trans('sale-performance.fields.deposit'))->min(0)->max(999999)->required();
                $form->number('balance', trans('sale-performance.fields.balance'))->min(0)->max(999999)->required();
                $form->hidden('money');
            }

            $form->number('arrears')->min(0.00)->max(999999)->default(0)->required();
            $form->datetime('refund_time');
            $form->switch('timely');
            //$form->switch('sale_lecturer');
            $form->datetime('created_at');
            //$form->hidden('pay_images');
            //$form->hidden('financial_audit');

            $form->saving(function (Form $form) {
                $input = $form->input();
                $form->pay_images = '';
                if (request('pay_images_str')) {
                    $images = explode(',', request('pay_images_str'));
                    foreach ($images as $key => $value) {
                        if (filter_var($value, FILTER_VALIDATE_URL) !== false) {
                            $images[$key] = Str::replace(getAliOssDomain(), '', Arr::first(explode('?', $value)));
                        }
                    }
                    $form->pay_images = json_encode($images);
                }
                if (isset($input['pay_number']) && \App\Models\SalePerformance::query()->where('pay_number', $input['pay_number'])->where('id', '!=', $form->getKey())->exists()) {
                    throw new AdminInvalidRequestException('付款单号已存在');
                }
                if (isset($input['deposit']) && isset($input['balance'])) {
                    $form->money = $form->deposit + $form->balance;
                }
            });
            $form->ignore(['type_str', 'pay_images_str', 'full_payment_str']);
        });
    }

}
